package com.leo.interview;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 错误的例子！！！！！
 *      原因：将permit作为lock，也作为判断的条件谓词，发生了不能读取的冲突
 *      改进：Interview4_2
 * @author xuexiaolei
 * @version 2017年11月06日
 */
public class Interview4 {
    private static final int COUNT = 50;
    private static Boolean permit = Boolean.TRUE;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newSingleThreadExecutor();
        exec.execute(new Runnable() {
            @Override public void run() {
                for (int i = 0; i < COUNT; i++) {
                    synchronized (permit) {
                        while (!permit) {
                            try {
                                permit.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                        System.out.println("子线程循环十次");
                        permit = Boolean.FALSE;
                        permit.notifyAll();
                    }
                }
                System.out.println("子线程结束");
            }
        });
        for (int i = 0; i < COUNT; i++) {
            synchronized (permit) {
                while (permit) {
                    try {
                        System.out.println("主线程等待");
                        permit.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("主线程循环一百次");
                permit = Boolean.TRUE;
                permit.notifyAll();
            }
        }
        System.out.println("主线程结束");
        exec.shutdown();
    }
}
